﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Data;
namespace VM.Common.Result
{
    /// <summary>
    /// 单个Datatable
    /// </summary>
    public class JsonFormat
    {
        public static JObject JsonResult(string Status, DataTable dtb, string ErroMes)
        {
            JObject JsonResult = new JObject()
                        {
                            new JProperty("IsSuccess",Status),
                            new JProperty("Msg",ErroMes)
                        };
            JsonResult.Add(new JProperty("data", ToJArray(dtb)));

            return JsonResult;
        }
        public static JArray ToJArray(DataTable dt)
        {
            JArray ja = new JArray();
            JObject jo = new JObject();
            try
            {
                if (dt != null)
                {
                    foreach (DataRow dataRow in dt.Rows)
                    {
                        jo = new JObject();
                        foreach (DataColumn dataColumn in dt.Columns)
                        {
                            jo.Add(new JProperty(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString()));

                        }
                        ja.Add(new JObject(jo));
                    }
                    return ja;
                }
                else
                {
                    ja.Add(new JValue(""));

                    return ja;
                }
                
                
            }
            catch
            {
                //ja.Add(null);
                ja.Add(new JValue(""));

                return ja;
            }
        }
    }
}


